<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use App\Statistics;
use App\Output;
use App\Faker;

class Count extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计每天每个UID下的设备数量';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $res = Statistics::groupBy('uid')->get([DB::raw('count(distinct deviceId) as num'), 'uid']);

        if ($res->isEmpty()) {
            dd('暂无数据');
        }

        $res = $res->toArray();

        $arr = [];
        foreach ($res as $e => $v) {
            // var_dump($v['num']);
            $tmp              = [];
            $tmp['uid']       = $v['uid'];
            $tmp['deviceNum'] = $v['num'];
            $tmp['day']       = date('Y-m-d');
            $arr[]            = $tmp;
        }

        try {
            $r = DB::table('outputs')->insert($arr);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }

        if (!$r) {
            dd('插入数据未成功');
        }

        dd('success!');
    }
}
